// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
var index = 0;
var lats = new Array();
var area;

google.load("maps", "3",  {
    callback: initialize,
    other_params:"sensor=false"
});


function initialize() {
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    geocoder = new google.maps.Geocoder();
    if (google.loader.ClientLocation) {
        latlng = new google.maps.LatLng(google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude);
    }
    var user_location = latlng.lat() + " " + latlng.lng();

        var oFormObject = document.forms[0];
		if(oFormObject)
		{
        	var oFormElement = oFormObject.elements["locationUser"].value = user_location;
		}

        var myOptions = {
        zoom: 8,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var map = new google.maps.Map(document.getElementById("map_canvas"),
    myOptions);

    google.maps.event.addListener(map, 'click', function(event) {
        if(index < 4){
            lats[index] = event.latLng;
            index++;

            if(index == 4){
                area = new google.maps.Polygon({
                    path: lats,
                    trokeColor: "#FF0000",
                    strokeOpacity: 0.8,
                    strokeWeight: 2,
                    fillColor: "#FF0000",
                    fillOpacity: 0.35
                });
                area.setMap(map);
                var str = "";
                for(var i = 0; i < lats.length; i++){
                    str += lats[i].lat() + "," + lats[i].lng() + ",";
                }
                var oFormObject = document.forms[0];
                var oFormElement = oFormObject.elements["questionnaire_location"].value = str;

                var param = "x1=" + lats[0].lat() + "," + lats[0].lng() + "&x2=" + lats[1].lat() + "," + lats[1].lng() + "&y1=" + lats[2].lat() + "," + lats[2].lng() + "&y2=" + lats[3].lat() + "," + lats[3].lng();
                new Ajax.Updater({
                    success: 'usersSurvey'
                }, '/users', {
                    method: 'get',
                    parameters: param
                });

            }
        }
    });
}
